package com.buaa.pm.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.buaa.pm.common.BusinessException;
import com.buaa.pm.common.ResponseCode;
import com.buaa.pm.config.activemq.ActivemqQueueConstant;
import com.buaa.pm.entity.*;
import com.buaa.pm.enumeration.PaperStatus;
import com.buaa.pm.enumeration.ProjectStatus;
import com.buaa.pm.feign.ParagraphClient;
import com.buaa.pm.mapper.PaperMapper;
import com.buaa.pm.model.PageModel;
import com.buaa.pm.model.dto.ParagraphRequestDTO;
import com.buaa.pm.model.dto.ProjectInfoDTO;
import com.buaa.pm.service.*;
import com.buaa.pm.util.CmdUtils;
import com.buaa.pm.util.RequestUtils;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class PaperServiceImpl extends ServiceImpl<PaperMapper, Paper> implements PaperService {

    private static final String DIR_ROOT_PATH = "tmp";

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Autowired
    private OssFileService ossFileService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private ParagraphService paragraphService;

    @Autowired
    private ParagraphClient paragraphClient;

    @Autowired
    private MarkedParagraphService markedParagraphService;

    @Autowired
    private DoiOSSFileService doiOSSFileService;

    @Override
    public void upload(String projectId, MultipartFile[] files) {
        if (projectService.getProjectById(projectId) == null) {
            throw new BusinessException(ResponseCode.PROJECT_NOT_EXIST);
        }
        for (MultipartFile file : files) {
            Paper paper = new Paper();
            paper.setProjectId(projectId);
            paper.setFilename(FilenameUtils.removeExtension(file.getOriginalFilename()));

            //查询标注数据
            QueryWrapper<MarkedParagraph> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(MarkedParagraph::getFileName,paper.getFilename());
            List<MarkedParagraph> markedParagraphList = markedParagraphService.list(queryWrapper);

            //有标注
            if (markedParagraphList.size()>0){
                //存文件
                String doi = markedParagraphList.get(0).getDoi();
                QueryWrapper<DoiOSSFile> doiQueryWrapper = new QueryWrapper<>();
                doiQueryWrapper.lambda().eq(DoiOSSFile::getDoi,doi.toLowerCase());
                DoiOSSFile doiOSSFile = doiOSSFileService.list(doiQueryWrapper).get(0);

                paper.setPdfId(doiOSSFile.getPdfFileId());
                paper.setHtmlId(doiOSSFile.getHtmlFileId());
                paper.setTxtId(doiOSSFile.getTxtFileId());

                if(save(paper)){
                    //存合成段
                    for(MarkedParagraph markedParagraph : markedParagraphList){
                        Paragraph paragraph = new Paragraph();
                        paragraph.setProjectId(paper.getProjectId());
                        paragraph.setPaperId(paper.getId());
                        paragraph.setPaperName(paper.getFilename());
                        paragraph.setContent(markedParagraph.getParagraph());
                        paragraph.setMofId(markedParagraph.getMofId());
                        paragraphService.save(paragraph);
                    }
                    paper.setStatus(PaperStatus.PARAGRAPH_FINISH);
                    updateById(paper);
                }

            }
            //无标注
            else {
                OssFile ossFile = ossFileService.uploadPdfFile(file);
                paper.setPdfId(ossFile.getId());
                paper.setStatus(PaperStatus.WAITING);
                if (save(paper)) {
                    jmsMessagingTemplate.convertAndSend(ActivemqQueueConstant.FILE_CONVERT_QUEUE, paper);
                }
            }
        }
    }

    @Override
    public PageModel<Paper> pagePaper(String projectId, int pageNum, int pageSize) {
        IPage<Paper> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Paper> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Paper::getProjectId, projectId);
        queryWrapper.lambda().orderByDesc(Paper::getCreatedAt);
        return PageModel.convert(page(page, queryWrapper));
    }

    @Override
    public boolean removePapers(List<String> ids) {
        if (ids.isEmpty()) {
            return false;
        }
        Paper paper = getById(ids.get(0));
        return removeBatchByIds(ids);
    }

    @Override
    public List<Paper> listFinishPaperByProject(String projectId) {
        QueryWrapper<Paper> queryWrapper = new QueryWrapper<>();

        queryWrapper.lambda().eq(Paper::getProjectId, projectId).eq(Paper::getStatus, PaperStatus.PARAGRAPH_FINISH);
        return list(queryWrapper);
    }

    @Override
    public Paper getPaperById(String id) {
        Paper paper = getById(id);
        if (paper == null) {
            throw new BusinessException(ResponseCode.PAPER_NOT_EXIST);
        }
        return paper;
    }

    @JmsListener(destination = ActivemqQueueConstant.FILE_CONVERT_QUEUE)
    public void receivePaper(Paper paper) {
        OssFile ossFile = ossFileService.getById(paper.getPdfId());
        String randomDirPath = DIR_ROOT_PATH + "/" + UUID.randomUUID().toString().replaceAll("-", "");
        try {
            FileUtils.forceMkdir(new File(randomDirPath));
            FileUtils.copyInputStreamToFile(ossFileService.getStream(ossFile), new File(randomDirPath + "/" + ossFile.getFilename()));
            String filenameWithoutExt = FilenameUtils.removeExtension(ossFile.getFilename());
            pdf2html(randomDirPath, filenameWithoutExt);
            html2txt(randomDirPath, filenameWithoutExt);
            OssFile htmlFile = ossFileService.uploadHtmlFile(new File(randomDirPath + "/" + filenameWithoutExt + ".html"));
            OssFile txtFile = ossFileService.uploadTxtFile(new File(randomDirPath + "/" + filenameWithoutExt + ".txt"));
            paper.setHtmlId(htmlFile.getId());
            paper.setTxtId(txtFile.getId());

            paper.setStatus(PaperStatus.CONVERT_FINISH);

            updateById(paper);

//            //查询标注数据
//            QueryWrapper<MarkedParagraph> queryWrapper = new QueryWrapper<>();
//            queryWrapper.lambda().eq(MarkedParagraph::getFileName,paper.getFilename());
//            List<MarkedParagraph> markedParagraphList = markedParagraphService.list(queryWrapper);

//            if (markedParagraphList.size()>0){
//                for(MarkedParagraph markedParagraph : markedParagraphList){
//                    Paragraph paragraph = new Paragraph();
//                    paragraph.setProjectId(paper.getProjectId());
//                    paragraph.setPaperId(paper.getId());
//                    paragraph.setPaperName(paper.getFilename());
//                    paragraph.setContent(markedParagraph.getParagraph());
//                    paragraphService.save(paragraph);
//                }
//                paper.setStatus(PaperStatus.PARAGRAPH_FINISH);
//                updateById(paper);
//            }
//            else {
                //没有标注过的文章
                //合成段落提取队列
            Paragraph paragraph = new Paragraph();
            paragraph.setProjectId(paper.getProjectId());
            paragraph.setPaperId(paper.getId());
            paragraph.setPaperName(paper.getFilename());
            paragraph.setContent("");
            if (paragraphService.save(paragraph)) {
                jmsMessagingTemplate.convertAndSend(ActivemqQueueConstant.PARA_EXTRACT_QUEUE, paragraph);
            }
//            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            paper.setStatus(PaperStatus.CONVERT_FAIL);
            paper.setHtmlId("");
            paper.setTxtId("");
            updateById(paper);
        } finally {
            try {
                FileUtils.deleteDirectory(new File(randomDirPath));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void pdf2html(String dir, String filenameWithoutExt) throws IOException {
        CommandLine commandLine = new CommandLine("pdf2htmlEX");
        commandLine.addArgument("--fit-width");
        commandLine.addArgument("600");
        commandLine.addArgument("${FILE}");
        HashMap<String, File> map = new HashMap<>();
        map.put("FILE", new File(dir + "/" + filenameWithoutExt + ".pdf"));
        commandLine.setSubstitutionMap(map);
        CmdUtils.runCommandLineInDir(commandLine, new File(dir));
    }

    private void html2txt(String dir, String filenameWithoutExt) throws IOException {
        CommandLine commandLine = new CommandLine("node");
        commandLine.addArgument("${EXE}");
        commandLine.addArgument("${FILE}");
        HashMap<String, File> map = new HashMap<>();
        map.put("EXE", new File("convert.js"));
        map.put("FILE", new File(dir + "/" + filenameWithoutExt + ".html"));
        commandLine.setSubstitutionMap(map);
        CmdUtils.runCommandLine(commandLine);
    }

    @JmsListener(destination = ActivemqQueueConstant.PARA_EXTRACT_QUEUE)
    public void receiveParagraph(Paragraph paragraph) {
        Paper paper = getById(paragraph.getPaperId());
        OssFile ossFile = ossFileService.getById(paper.getTxtId());

        ParagraphRequestDTO paragraphRequestDTO = new ParagraphRequestDTO();
        paragraphRequestDTO.setFile_name(ossFile.getObjectName());
        paragraphRequestDTO.setFile_path("txt");


        //发送合成段提取请求
        try{
            JSONObject jsonObject = paragraphClient.getParagraph(paragraphRequestDTO);
            JSONArray dataArray = jsonObject.getJSONArray("data");
            // 处理data空
            if(dataArray.size()==0){
                paragraphService.removeById(paragraph);
                paper.setStatus(PaperStatus.PARAGRAPH_FAIL);
            }
            else {
                for (int i = 0; i < dataArray.size(); i++) {
                    String dataElement = dataArray.getString(i);
                    if(i == 0){
                        paragraph.setContent(dataElement);
                        paragraphService.updateById(paragraph);
                    }
                    else {
                        Paragraph newParagraph = new Paragraph();
                        newParagraph.setProjectId(paper.getProjectId());
                        newParagraph.setPaperId(paper.getId());
                        newParagraph.setPaperName(paper.getFilename());
                        newParagraph.setContent(dataElement);
                        paragraphService.save(newParagraph);
                    }
                }
                //更新论文状态
                paper.setStatus(PaperStatus.PARAGRAPH_FINISH);
            }
            updateById(paper);
        }
        catch (Exception e){
            List<Paragraph> paragraphList = paragraphService.listParagraphByPaper(paper.getId());
            for (Paragraph NullParagraph : paragraphList){
                paragraphService.removeById(NullParagraph);
            }
            paper.setStatus(PaperStatus.PARAGRAPH_FAIL);
            updateById(paper);
        }
    }


    @Override
    public Project quickStart(@RequestParam MultipartFile[] files){
        // 获取当前时间的时间戳
        long timestamp = System.currentTimeMillis();

        // 创建SimpleDateFormat对象，用于格式化时间戳字符串
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd-HH:mm:ss");

        // 格式化时间戳为字符串
        String timestampString = formatter.format(new Date(timestamp));

        // 初始化项目信息
        ProjectInfoDTO projectInfoDTO = new ProjectInfoDTO();
        projectInfoDTO.setName(timestampString);
        projectInfoDTO.setIntroduction("快速创建于：" + timestampString);

        // 新建项目
        Project project = new Project();
        BeanUtils.copyProperties(projectInfoDTO, project);
        project.setStatus(ProjectStatus.PAPER_CONVERT);
        if (projectService.save(project)) {
            upload(project.getId(),files);
        }
        return project;
    }

    @Override
    public List<Paper> listPaperByProject(String projectId) {
        QueryWrapper<Paper> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Paper::getProjectId, projectId);
        queryWrapper.lambda().orderByDesc(Paper::getStatus);
        return list(queryWrapper);
    }
}
